import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Iterator;

/**
 * @desctiption
 * @Author bjweitingting
 * @date 2018/4/25
 **/
public class JacksonTest {
    //    /throws JsonParseException, JsonMappingException, IOException
    public static void main(String[] args) throws IOException {
        String json = "{\"username\":\"zhangsan\",\"性别\":\"男\",\"company\":{\"companyName\":\"中华\",\"address\":\"北京\"},\"cars\":[\"奔驰\",\"宝马\"]}";
        ObjectMapper mapper = new ObjectMapper();
        //JSON ----> JsonNode
        JsonNode rootNode = mapper.readTree(json);
        Iterator<String> keys = rootNode.fieldNames();
        System.out.println(rootNode.get("username"));

        while (keys.hasNext()) {
            String fieldName = keys.next();
            System.out.println(fieldName + ": " + rootNode.path(fieldName).toString());
        }
        //JsonNode ----> JSON
        System.out.println(mapper.writeValueAsString(rootNode));
        //test
        stringToObject(json);
    }

    public static void stringToObject(String testString) {
        //ObjectMapper反序列化时，如果json字符串中字段少，则实例相应值为null，不会报异常；
        //如果json字符串中字符值多，则会报异常，需要进行相应配置
        ObjectMapper objectMapper = new ObjectMapper();
        //反序列化时，忽略json中多余的字段，不会报异常
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //字符串转对象，
        try {
            User user = objectMapper.readValue(testString, User.class);
            System.out.println(user.getUserName());
            System.out.println(user.getAge());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class User {
    String userName;

    Integer age;

    public String getUserName() {
        return userName;
    }

    @JsonProperty("username")
    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
